package com.atguigu.day03;

import com.atguigu.bean.Event;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink06_TransForm_Max_MaxBy {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.将从端口读出来的数据转为JavaBean
        SingleOutputStreamOperator<Event> eventStream = streamSource.map(new MapFunction<String, Event>() {
            @Override
            public Event map(String value) throws Exception {
                String[] split = value.split(",");
                return new Event(split[0], split[1], Long.parseLong(split[2]));
            }
        });

        //4.将相同用户的数据聚合到一块
        KeyedStream<Event, String> keyedStream = eventStream.keyBy(new KeySelector<Event, String>() {
            @Override
            public String getKey(Event value) throws Exception {
                return value.user;
            }
        });

        //TODO 5.使用聚合算子max 以及 maxby求每个用户最大的时间戳
//        SingleOutputStreamOperator<Event> result = keyedStream.max("timestamp");
        SingleOutputStreamOperator<Event> result = keyedStream.maxBy("timestamp",false);

        result.print("maxBy-false");

        env.execute();
    }
}
